import { GuildChannel } from "api/structures/GuildChannel";
import { Snowflake } from "api/structures/utils/Snowflake";

interface GuildListModel {
    id: string
    channelName: string
    userAvatar: string
    itemEnabled: boolean
}

declare const guildChannelListModel: Qml.ListModel<GuildListModel>;
declare const listChannel1View: Qml.ListView;
declare const listChannel2View: Qml.ListView;

export function handleReady(guild_id: string) {
    // window.client.on("ready", handleClientReady)

    window.client.emit("debug", "GuildPAge.handleReady="+guild_id)

    handleClientReady(guildChannelListModel, guild_id)
}

function handleDestroy() {
    // window.client.off("ready", handleClientReady)
}

function showChannel(id: string) {
    window.client.emit("debug", "Show guild channel " + id)
    window.pageStack.push("./BasicChat.qml", { chat_id: id }) as Qml.Page;
}

export function handleClientReady(model: Qml.ListModel<GuildListModel>, guild_id: string) {

    model.clear();

    //@ts-ignore
    console.log("TTT guildChannelListModel=" + window.guildChannelListModel)
    //@ts-ignore
    console.log("TTT listChannel1View=" + window.listChannel1View)
    //@ts-ignore
    console.log("TTT listChannel2View=" + window.listChannel2View)

    try {

        window.client.emit("debug", "start dms")

        // channel.type
        //     0 basic
        //     2 voice
        //     4 channels folder
        //     5 anouncement
        //     15 topics

        const folders: string[] = []
        const foldersData: Record<string, string[]> = {}
        const completeOrder: string[] = []

        const resultIds: string[] = []

        const channelIds: string[] = Object.keys(window.client.guilds[guild_id].channels)

        // Find folders first
        channelIds.forEach(channelId => { 
            const channel = window.client.guilds[guild_id].channels[channelId]
            if (channel.type === 4) {
                folders.push(channel.id)
                completeOrder.push(channel.id)
                foldersData[channel.id] = []
            }
        });

        // GroupUp by folders
        channelIds.forEach(channelId => { 
            const channel = window.client.guilds[guild_id].channels[channelId]
            if (channel.type !== 4) {
                if (channel.parent_id) {
                    foldersData[channel.parent_id].push(channel.id)
                } else {
                    completeOrder.push(channel.id)
                }
            }
        });


        folders.sort((a_id, b_id) => {
            const a = window.client.guilds[guild_id].channels[a_id];
            const b = window.client.guilds[guild_id].channels[b_id];
            return a.position - b.position;
        })

        folders.forEach((id)=>{
            foldersData[id].sort((a_id, b_id) => {
                const a = window.client.guilds[guild_id].channels[a_id];
                const b = window.client.guilds[guild_id].channels[b_id];
                return a.position - b.position;
            })
        })

        completeOrder.sort((a_id, b_id) => {
            const a = window.client.guilds[guild_id].channels[a_id];
            const b = window.client.guilds[guild_id].channels[b_id];
            return a.position - b.position;
        })

        
        completeOrder.forEach((id)=>{
            const a = window.client.guilds[guild_id].channels[id];
            if (a.type === 4) {
                resultIds.push(id)
                foldersData[id].forEach((id2)=>{
                    resultIds.push(id2)
                })
            } else {
                resultIds.push(id)
            }
        })

        // channelIds.forEach(channelId => { 
        //     const channel = window.client.guilds[guild_id].channels[channelId]

        //     if (channel.type !== 4) {

        //     }
        // }


        const dms = resultIds.map((id)=>{
            return window.client.guilds[guild_id].channels[id]
        })
        .map((channel, index, arr) => {

            // window.client.emit("debug", "start pushing data " + index + "/" + arr.length)

            //https://discord.com/assets/641edf794e368d5e8180.png
            
            let tag = ""
            let typeName = ""
            let icon = ""
            let disable = false;
            switch (channel.type) {
                case 2: 
                    // tag = "*";
                    // typeName = "audio: ";
                    disable = true;
                    icon = "image://theme/icon-s-reject"
                    break
                case 4:
                    tag = ">"
                    // typeName = "folder: ";
                    disable = true;
                    break
                case 5:
                    // tag = "!!"
                    // typeName = "anonce: ";
                    icon = "image://theme/icon-s-alarm"
                    break
                case 15:
                    // tag = "[]"
                    // typeName = "thread: ";
                    disable = true;
                    icon = "image://theme/icon-s-chat"
                    break
                case 0:
                    // tag = "#"
                    // typeName = "chat: "
                    icon = "image://theme/icon-s-message"
                    break
                default:
                    tag = "???"
                    typeName = "unknown("+channel.type+"): "
                    disable = true;
                    break
            }

            try {
                return {
                    id: channel.id,
                    userAvatar: icon,
                    channelName: tag + typeName + channel.name,
                    itemEnabled: !disable
                }
            } catch(err: any) {
                window.client.emit("debug", "2: Error " + JSON.stringify(err) + ", " + err.message + ", " + err.stack)
                return {
                    id: channel.id,
                    userAvatar: "",
                    channelName: "Error "+channel.id,
                    itemEnabled: false
                }
            }
        });

        window.client.emit("debug", "ended dms.size " + dms.length)

        dms.forEach((dm, index) => {
            // window.client.emit("debug", "listModel.append " + index + "/" + dms.length)
            model.append(dm)
        });
    } catch(err: any) {
        window.client.emit("debug", "2: Error " + JSON.stringify(err) + ", " + err.message + ", " + err.stack)
    }
}